#include "stopwatch.h"
#include <8052.h>
#include <stdint.h>

uint8_t counting_up = 1;
uint8_t counting_flag = 1;
uint8_t counting_underflow_flag = 0;

int8_t stopwatch_hr, stopwatch_min, stopwatch_sec; // 秒表、倒计时模式下的时间
int8_t stopwatch_sec_frac; // 秒表、倒计时模式下的秒的小数部分

void counting_loop() {
    if (counting_flag) {
        if (counting_up) {
            ++stopwatch_sec_frac;
            if (stopwatch_sec_frac >= 100) {
                stopwatch_sec_frac = 0;
                ++stopwatch_sec;
                if (stopwatch_sec >= 60) {
                    stopwatch_sec = 0;
                    ++stopwatch_min;
                    if (stopwatch_min >= 60) {
                        stopwatch_min = 0;
                        ++stopwatch_hr;
                    }
                }
            }
        } else {
            --stopwatch_sec_frac;
            // TODO 处理计时为0
            if (stopwatch_sec_frac < 0) {
                stopwatch_sec_frac = 99;
                --stopwatch_sec;
                if (stopwatch_sec < 0) {
                    stopwatch_sec = 59;
                    --stopwatch_min;
                    if (stopwatch_min < 0) {
                        stopwatch_min = 59;
                        --stopwatch_hr;
                    }
                }
            }
            if (stopwatch_hr < 0) { // 如果计时结束
                stopwatch_hr = stopwatch_min = stopwatch_sec = stopwatch_sec_frac = 0; // 清除计时
                counting_underflow_flag = 1; // 设置计时结束标志
                counting_flag = 0; // 停止计时
            }
        }
    }
}
